// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameMgr from './GameManager'
import Monster from './Monster'
import Role from './Player'

const { ccclass } = cc._decorator

@ccclass
export default class SceneMain extends cc.Component {
  layoutTopBgc: cc.Node[] = []

  bgcSpeed: number = 300

  lastDistanceDiff: number = 10000

  onLoad() {}

  async start() {
    this.handleBgcMove()
    await this.initRole()
    this.initPannel()
    GameMgr.showToast(this.node, '我是标题', '我是按钮', () => {
      console.log('我是回调函数')
    })
  }

  handleBgcMove() {
    const layoutTopBgc1 = this.node.getChildByName('layout_top').getChildByName('top_bgc1')
    const layoutTopBgc2 = this.node.getChildByName('layout_top').getChildByName('top_bgc2')
    GameMgr.instance.canLayoutTopBgcMove = true
    this.layoutTopBgc = [layoutTopBgc1, layoutTopBgc2]
  }

  startMoveBgc(dt) {
    if (GameMgr.instance.canLayoutTopBgcMove) {
      this.layoutTopBgc[0].x -= dt * this.bgcSpeed
      this.layoutTopBgc[1].x -= dt * this.bgcSpeed
      if (this.layoutTopBgc[0].x < -this.layoutTopBgc[0].width) {
        this.layoutTopBgc[0].x = this.layoutTopBgc[1].x + this.layoutTopBgc[0].width / 2 + this.layoutTopBgc[1].width / 2
      }
      if (this.layoutTopBgc[1].x < -this.layoutTopBgc[1].width) {
        this.layoutTopBgc[1].x = this.layoutTopBgc[0].x + this.layoutTopBgc[0].width / 2 + this.layoutTopBgc[1].width / 2
      }
    }
  }

  async initRole() {
    GameMgr.instance.layoutTop = this.node.getChildByName('layout_top')
    await new Monster().init()
    await new Monster().init()
    await new Monster().init()
    const role = new Role()
    await role.init()
    GameMgr.instance.roleInstance = role
    this.moveMonsterToRole()
    // setTimeout(() => {
    //   GameMgr.instance.roleInstance.roleName = 'doushi'
    // }, 3000)
    // setTimeout(() => {
    //   GameMgr.instance.roleAnimation.play('attack')
    // }, 5000)
  }

  moveMonsterToRole() {
    const MonstersAlive = GameMgr.instance.MonstersAlive
    MonstersAlive.forEach(item => {
      cc.tween(item.node)
        .to((Math.abs(item.node.x) + Math.abs(GameMgr.instance.roleNode.position.x)) / 200, { position: cc.v3(GameMgr.instance.roleNode.position.x + GameMgr.instance.roleNode.width, item.node.y) })
        .call(() => {
          const animation = item.node.getComponent(cc.Animation)
          animation.play('attack')
        })
        .start()
    })
  }

  initPannel() {
    const layoutCenter = this.node.getChildByName('layout_center').getChildByName('center_bgc')
    const totalPowerLabel = layoutCenter.getChildByName('total_power_label').getComponent(cc.Label)
    GameMgr.instance.totalPowerLabel = totalPowerLabel
    // 战力 需要结合各方面计算 先按攻击 后续改
    totalPowerLabel.string = '战力：' + GameMgr.instance.roleInstance.ATK
    const pannelContent = layoutCenter.getChildByName('scroll_view_box').getChildByName('view').getChildByName('content')
    GameMgr.instance.pannelContent = pannelContent
  }

  /**
   * 检测是否存在怪兽 存在且在攻击范围内 就会攻击
   *
   */
  checkCanAttack() {
    return GameMgr.instance.MonstersAlive.length != 0 && GameMgr.instance.roleInstance instanceof Role
  }

  /**
   * 子弹自动
   *
   */
  autoBulletAttack(bullet: cc.Node) {
    GameMgr.instance.roleInstance.bullet.active = true
    const MonstersAlive = GameMgr.instance.MonstersAlive
    const targetPos = MonstersAlive[0].node.getPosition()
    const bulletPos = bullet.getPosition()
    let dirVe3 = targetPos.subtract(bulletPos)
    if (dirVe3.x <= 0) {
      bullet.setPosition(-225, 185)
      MonstersAlive[0].target.getHurtHP(MonstersAlive[0].node)
      if (GameMgr.instance.MonstersAlive.length === 0) GameMgr.instance.roleInstance.bullet.active = false
      return
    }
    let dir: cc.Vec2 = dirVe3.normalize()
    let newPos = bulletPos.add(dirVe3.x < 30 ? dir.multiplyScalar(3) : dir.multiplyScalar(5))
    bullet.setPosition(newPos)
  }

  update(dt) {
    this.startMoveBgc(dt)
    if (this.checkCanAttack()) {
      if (GameMgr.instance.roleInstance.bullet == null) {
        GameMgr.instance.roleInstance.addBullet()
      }
      this.autoBulletAttack(GameMgr.instance.roleInstance.bullet)
    }
  }
}
